<template>
    
    <div style="margin-top: 20px;">
        <!-- 养殖信息 -->
        <div >
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;float: left;margin-right: 20px">养殖信息</h3>
                <el-button style="float:left;" @click="addInfo">设置</el-button>
            </div>
            <br><br><hr><br>
            <div style="float: left;width: 300px;">
                <h4>品种 : {{ data.ciVariety }}</h4>
            </div>
            <div style="float: left;">
                <h4>来源 : {{ data.ciSource }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 300px;">
                <h4>饲养天数 : {{ data.ciFeedDay }}天</h4>
            </div>
            <div style="float: left;">
                <h4>饲料品牌 : {{ data.ciFeedVariety }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 300px;">
                <h4>饲料负责人 : {{ data.ciFeedPeople }}</h4>
            </div>
            <div style="float: left;">
                <h4>出栏日期 : {{ data.ciDate }}</h4>
            </div>
            <br><br>

        </div>

        <!-- 保健信息 -->
        <div style="float: left;width: 100%;">
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;float: left;margin-right: 20px">保健信息</h3>
                <el-button style="float:left;" @click="addsImm">新增行</el-button>
            </div>
            <br><br><hr><br>
            <div style="float: left;overflow: auto;height: 180px;width: 100%;text-align: left;">
                <table>
                    <tr>
                        <th style="width: 200px;">饲养天数</th>
                        <th style="width: 200px;">免疫方式</th>
                        <th style="width: 200px;">免疫方式</th>
                        <th style="width: 200px;">操作</th>
                    </tr>
                    <tr v-for="item in ImmInfo" :key="item" style="text-align: left;">
                        <td>{{ item.immuneDay }}</td>
                        <td>{{ item.immuneName }}</td>
                        <td>{{ item.immuneMode }}</td>
                        <td>
                          <el-link @click="upd(item)">修改</el-link>&nbsp;
                          <el-link @click="del(item.immuneId)">删除</el-link>
                        </td>
                    </tr>
                    <tr v-show="addImm" style="text-align: left;">
                        <td>
                          <input type="text" v-model="Imm.immuneDay">  
                        </td>
                        <td>
                          <input type="text" v-model="Imm.immuneName">
                        </td>
                        <td>
                          <input type="text" v-model="Imm.immuneMode">
                        </td>
                        <td>
                          <el-link @click="bc">保存</el-link>&nbsp;
                          <el-link @click="qx">取消</el-link>
                        </td>
                    </tr>
                </table>
            </div>
            <br>

        </div>

        <!-- 动检证 -->
        <div :style="computedHeight">
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;">动检证</h3>
            </div>
            <br><hr><br>
            <div>
              <el-upload v-model:file-list="fileList" :action="lis" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-success="handleUploadSuccess"
                        :on-error="handleUploadError" :on-remove="handleRemove">
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full style="width: 80%; height: 80%;" :src="dialogImageUrl" alt="Preview Image"/>
                    </el-dialog>
            </div>
        </div>

        
        <!-- 企业信息 -->
        <div style="float:left;width: 100%;">
          <br>
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;float: left;margin-right: 20px">企业信息</h3>
                <el-button style="float:left;" @click="addInfoyz">设置</el-button>
            </div>
            <br><br><hr><br>
            <div style="float: left;width: 300px;">
                <h4>养殖场 : {{ datayz.eName }}</h4>
            </div>
            <div style="float: left;">
                <h4>负责人 : {{ datayz.ePeople }}</h4>
            </div>
            <br><br>
            <div style="float: left;width: 300px;">
                <h4>存栏数量 : {{ datayz.eNum }}只</h4>
            </div>
            <br><br>

        </div>

        <!-- 企业图片 -->
        <div :style="computedHeightqy">
          <br>
            <div>
                <h3 style="font-weight: bold;color:deepskyblue;">企业图片</h3>
            </div>
            <br><hr><br>
            <div>
              <el-upload v-model:file-list="fileListqy" :action="lisqy" list-type="picture-card"
                        :on-preview="handlePictureCardPreviewqy" :on-success="handleUploadSuccessqy"
                        :on-error="handleUploadErrorqy" :on-remove="handleRemoveqy">
                        <el-icon><Plus /></el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisibleqy">
                        <img w-full style="width: 80%; height: 80%;" :src="dialogImageUrlqy" alt="Preview Image"/>
                    </el-dialog>
            </div>
        </div>

    </div>
    

    <!-- 设置养殖信息 -->
  <el-dialog v-model="addshow" title="养殖信息" style="max-width: 600px;height: 450px">
    <el-form ref="ruleFormRef" style="max-width: 100%;height: 100px" :model="input"
    :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="品种" prop="ciVariety">
      <el-input v-model="input.ciVariety" />
    </el-form-item>
    <el-form-item label="来源" prop="ciSource">
      <el-input v-model="input.ciSource" />
    </el-form-item>
    <el-form-item label="饲养天数" prop="ciFeedDay">
      <el-input v-model="input.ciFeedDay" />
    </el-form-item>
    <el-form-item label="饲养品牌" prop="ciFeedVariety">
      <el-input v-model="input.ciFeedVariety" />
    </el-form-item>
    <el-form-item label="饲养负责人" prop="ciFeedPeople">
      <el-input v-model="input.ciFeedPeople" />
    </el-form-item>
    <el-form-item label="出栏日期" prop="ciDate">
      <el-input type="date" v-model="input.ciDate" />
    </el-form-item>
    <br><hr><br>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="adds(ruleFormRef)">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <!-- 修改保健信息 -->
  <el-dialog v-model="updshow" title="保健信息" style="max-width: 600px;height: 300px" >
    <el-form style="max-width: 100%;height: 100px" :model="Imms"
     label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="饲养天数" prop="immuneDay">
      <el-input v-model="Imms.immuneDay" />
    </el-form-item>
    <el-form-item label="免疫方式" prop="immuneName">
      <el-input v-model="Imms.immuneName" />
    </el-form-item>
    <el-form-item label="免疫方式" prop="immuneMode">
      <el-input v-model="Imms.immuneMode" />
    </el-form-item>
    <br><hr><br>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="updImm(ruleFormRef)">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  
    <!-- 设置企业信息 -->
    <el-dialog v-model="addshowyz" title="企业信息" style="max-width: 600px;height: 450px">
    <el-form ref="ruleFormRefyz" style="max-width: 100%;height: 100px" :model="inputyz"
    :rules="rulesyz" label-width="auto" class="demo-ruleForm" :size="formSizeyz"
    status-icon >
    <el-form-item label="养殖场" prop="eName">
      <el-input v-model="inputyz.eName" />
    </el-form-item>
    <el-form-item label="负责人" prop="ePeople">
      <el-input v-model="inputyz.ePeople" />
    </el-form-item>
    <el-form-item label="存栏数量" prop="eNum">
      <el-input v-model="inputyz.eNum" />
    </el-form-item>
    <br><hr><br>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="addsyz(ruleFormRef)">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>


</template>
<script lang="ts" setup>
import{ref,onMounted,reactive,inject,computed } from 'vue'
import { type AxiosStatic } from 'axios';
const axios=inject('axios') as AxiosStatic
import { ElMessage,ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

onMounted(()=>{
    //console.log(localStorage.getItem('tmid'))
    Infoshows()//养殖信息
    Immshows()//保健信息
    shows()//动检证
    Infoshowsyz()//企业信息
    showsqy()//企业图片
})
// #region 养殖信息
const data=ref({})
//显示养殖信息
const Infoshows=()=>{
    axios.get('/Cultivation/GetCultivationInfo?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data,res.data.length)
        if(res.data.length>0){
            res.data[0].ciDate=res.data[0].ciDate.substring(0,10)
            data.value=res.data[0]
        }
        //console.log(data.value)
    })
}

const input=reactive({
  isDel: 0,
  ciVariety: "",
  ciSource: "",
  ciFeedDay: "",
  ciFeedVariety: "",
  ciFeedPeople: "",
  ciDate: "",
  tMid:localStorage.getItem('tmid')
})
//是否打开养殖信息
const addshow=ref(false)
//打开养殖信息弹框
const addInfo=()=>{
    //console.log(data.value.ciFeedPeople)
    addshow.value=true
    if(data.value.ciFeedPeople!=null){
            input.ciVariety=data.value.ciVariety
            input.ciSource=data.value.ciSource
            input.ciFeedDay=data.value.ciFeedDay
            input.ciFeedVariety=data.value.ciFeedVariety
            input.ciFeedPeople=data.value.ciFeedPeople
            input.ciDate=data.value.ciDate.substring(0,10)
            input.isDel=data.value.isDel
            input.tMid=data.value.tMid
        }
}


const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//非空
const rules = reactive<FormRules<RuleForm>>({
    ciVariety: [
    { required: true, message: '品种不能为空', trigger: 'blur' },
  ],
})
const adds = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
            axios.post('/Cultivation/AddCultivationInfo',input)
            .then((res)=>{
                //console.log(res.data)
                if(res.data>0){
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    addshow.value=false
                    Infoshows()
                }
            })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// #endregion

// #region 保健信息

const ImmInfo=ref([])
const addImm=ref(false)
//添加字段
const Imm=reactive({
  tMid:localStorage.getItem('tmid'),
  immuneMode:'',
  immuneName:'',
  immuneDay:'',
})
//修改字段
const Imms=reactive({
  tMid:localStorage.getItem('tmid'),
  immuneMode:'',
  immuneName:'',
  immuneDay:'',
  immuneId:0
})
//保健信息显示
const Immshows=()=>{
  axios.get('/Cultivation/GetImmune?tmid='+localStorage.getItem('tmid'))
  .then((res)=>{
    //console.log(res.data)
    ImmInfo.value=res.data
  })
}
//新增行
const addsImm=()=>{
  if(addImm.value==true){
    return ElMessage({
      message: '请先添加行数据并保存',
      type: 'warning',
    })
  }
  addImm.value=true
}
//删行
const qx=()=>{addImm.value=false}
//保存添加保健信息
const bc=()=>{
  if(Imm.immuneMode==''||Imm.immuneName==''||Imm.immuneDay==''){
    ElMessage({
      message: '请填写完整信息',
      type: 'warning',
    })
  }
  axios.post('/Cultivation/AddImmune',Imm)
  .then((res)=>{
    if(res.data>0){
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      addImm.value=false
      Imm.immuneMode=''
      Imm.immuneName=''
      Imm.immuneDay=''
      Immshows()
    }
  })
}
//删除
const del=(id:any)=>{
  axios.post('/Cultivation/Del?ids='+id)
  .then((res)=>{
    if(res.data>0){
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      Immshows()
    }
  })
}

const updshow=ref(false)

//打开弹框并反填数据
const upd=(item:any)=>{
  updshow.value=true
  Imms.tMid=localStorage.getItem('tmid')
  Imms.immuneMode=item.immuneMode
  Imms.immuneName=item.immuneName
  Imms.immuneDay=item.immuneDay
  Imms.immuneId=item.immuneId
}
//修改
const updImm = async (formEl: FormInstance | undefined) => {
  if(Imms.immuneDay==''||Imms.immuneName==''||Imms.immuneMode==''){
    ElMessage({
      message: '请填写完整信息',
      type: 'warning',
    })
  }
        axios.post('Cultivation/UpdImmune',Imms)
        .then(res=>{
            console.log(res.data)
            if(res.data>0){
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                updshow.value=false
                Immshows()
            }else{
                ElMessage({
                    message: '修改失败',
                    type: 'error',
                })
            }
        })
}

// #endregion 保健信息

//#region 动检证

const num=ref([])
//图片
const fileList = ref<UploadUserFile[]>([])
//显示
const shows=()=>{
    axios.get('/Cultivation/GetDynamic?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data)
        num.value=res.data.length
        if (Array.isArray(res.data)) {
        fileList.value = res.data.map((image) => ({
          name: image.did || 'default-name.jpeg',  // 根据需要设置图片名称
          url: image.durl
        }));
      } else {
        console.error('Unexpected response data format:', res.data);
      }
    })
}
const computedHeight=computed(()=> {
    shows()
    return {
        height: num.value < 7 ? '230px' : '390px', // 直接返回字符串
        alignItems: 'center',
        margin: '0 auto',
        float: 'left',
        width: '100%'
      };
    })

const lis = computed(() => {
  return fileList.value.length > 9 ? '' : 'http://182.92.209.50:8001/api/TraceManage/GetImage';
});
// 判断是否禁用上传按钮
//const isUploadDisabled = computed(() => fileList.value.length > 9);
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//删除图片
const handleRemove: UploadProps['onRemove'] = (url) => {
  console.log(url.name)
    axios.post('/Cultivation/DelDynamic?ids='+url.name)
    .then((res)=>{
        //console.log(res.data,num.value)
        if(num.value==7){
          shows()//动检证
      }
    })
}
//预览图片处理事件
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//上传成功后
const handleUploadSuccess=(url)=>{
  //console.log(url)
  axios.post('/Cultivation/AddDynamic',{
    tMid:localStorage.getItem('tmid'),
    durl:url,
    addName:"张三"
  })
  .then((res)=>{
    //console.log(res.data)
    if(num.value==6){
    shows()//动检证
    }
  })
}
//上传失败
const handleUploadError = (err) => {
    shows()
    if(num.value==9){
        ElMessage.error(`最多上传9张图片`);
    }else{
        ElMessage.error(`图片上传失败，请重试！`);
    }
};

//#endregion

// #region 企业信息
const datayz=ref({})
//显示企业信息
const Infoshowsyz=()=>{
    axios.get('/Cultivation/GetEnterprise?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
      datayz.value.eNum=0
        //console.log(res.data,res.data.length)
        if(res.data.length>0){
            // res.data[0].ciDate=res.data[0].ciDate.substring(0,10)
            datayz.value=res.data[0]
        }
        //console.log(data.value)
    })
}

const inputyz=reactive({
  eName: "",
  ePeople: "",
  eNum: '',
  tMid:localStorage.getItem('tmid')
})
//是否打开养殖信息
const addshowyz=ref(false)
//打开养殖信息弹框
const addInfoyz=()=>{
    //console.log(data.value.ciFeedPeople)
    addshowyz.value=true
    if(datayz.value.eNum!=null){
            inputyz.eNum=datayz.value.eNum
            inputyz.ePeople=datayz.value.ePeople
            inputyz.eName=datayz.value.eName
            inputyz.tMid=datayz.value.tMid
        }
}


const formSizeyz = ref<ComponentSize>('default')
const ruleFormRefyz = ref<FormInstance>()
//非空
const rulesyz = reactive<FormRules<RuleForm>>({
  eName: [
    { required: true, message: '养殖场不能为空', trigger: 'blur' },
  ],
})
const addsyz = async (formEl: FormInstance | undefined) => {
  if(inputyz.eName==''||inputyz.ePeople==''||inputyz.eNum==''){
    ElMessage({
            message: '养殖场信息不能为空',
            type: 'warning',
        })
  }
            axios.post('/Cultivation/AddEnterprise',inputyz)
            .then((res)=>{
                //console.log(res.data)
                if(res.data>0){
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    addshowyz.value=false
                    Infoshowsyz()
                }
            })
}

// #endregion

//#region 企业图片

const numqy=ref([])
//图片
const fileListqy = ref<UploadUserFile[]>([])
//显示
const showsqy=()=>{
    axios.get('/Cultivation/GetEnterpriseImg?tmid='+localStorage.getItem('tmid'))
    .then((res)=>{
        //console.log(res.data)
        numqy.value=res.data.length
        if (Array.isArray(res.data)) {
        fileListqy.value = res.data.map((image) => ({
          name: image.eIid || 'default-name.jpeg',  // 根据需要设置图片名称
          url: image.eurl
        }));
      } else {
        console.error('Unexpected response data format:', res.data);
      }
    })
}
const computedHeightqy=computed(()=> {
    showsqy()
    return {
        height: numqy.value < 7 ? '260px' : '410px', // 直接返回字符串
        alignItems: 'center',
        margin: '0 auto',
        float: 'left',
        width: '100%',
        // background: 'aqua'
      };
    })

const lisqy = computed(() => {
  return fileListqy.value.length > 9 ? '' : 'http://182.92.209.50:8001/api/TraceManage/GetImage';
});
// 判断是否禁用上传按钮
//const isUploadDisabled = computed(() => fileList.value.length > 9);
const dialogImageUrlqy = ref('')
const dialogVisibleqy = ref(false)
//删除图片
const handleRemoveqy: UploadProps['onRemove'] = (url) => {
  console.log(url.name)
    axios.post('/Cultivation/DelEnterpriseImg?ids='+url.name)
    .then((res)=>{
        //console.log(res.data,num.value)
        if(numqy.value==7){
          showsqy()//企业图片
      }
    })
}
//预览图片处理事件
const handlePictureCardPreviewqy: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrlqy.value = uploadFile.url!
  dialogVisibleqy.value = true
}
//上传成功后
const handleUploadSuccessqy=(url)=>{
  //console.log(url)
  axios.post('/Cultivation/AddEnterpriseImg',{
    tMid:localStorage.getItem('tmid'),
    eurl:url,
    addName:"张三"
  })
  .then((res)=>{
    //console.log(res.data)
    if(numqy.value==6){
          showsqy()//企业图片
    }
  })
}
//上传失败
const handleUploadErrorqy = (err) => {
    shows()
    if(numqy.value==9){
        ElMessage.error(`最多上传9张图片`);
    }else{
        ElMessage.error(`最多上传9张图片！`);
    }
};

//#endregion







</script>